package com.reone.jsbridgedemo.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.EditText;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.reone.jsbridgedemo.R;
import com.reone.jsbridgedemo.activity.base.BaseActivity;
import com.reone.jsbridgedemo.utils.CmdUtil;
import com.reone.jsbridgedemo.utils.Utils;
import com.reone.jsbridgedemo.webview.JSBridgeWebView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangxingsheng on 2018/7/20.
 */
public class CmdActivity extends BaseActivity {
    @BindView(R.id.js_bridge_webView)
    JSBridgeWebView jsBridgeWebView;
    @BindView(R.id.edit_cmd)
    EditText editCmd;
    @BindView(R.id.content)
    TextView content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cmd);
        ButterKnife.bind(this);
        initWebView();
    }

    private void initWebView() {
        jsBridgeWebView.loadUrl(Utils.getAssetHtml("cmddemo.html"));
        jsBridgeWebView.getBridge().registerHandler("execCmd", new BridgeHandler() {
            @Override
            public void handler(String cmd, CallBackFunction function) {
                try {
                    talk("h5 exec cmd " + cmd);
                    String result = CmdUtil.execCmd(cmd);
                    function.onCallBack(Utils.result(result));
                } catch (Exception e) {
                    talk(e.getMessage());
                    function.onCallBack(e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick(R.id.btn_exec)
    public void onViewClicked() {
        try {
            String cmd = Utils.getTextFromEdit(editCmd);
            talk("exec cmd " + cmd);
            String result = CmdUtil.execCmd(cmd);
            content.setText(Utils.result(result));
        } catch (Exception e) {
            talk(e.getMessage());
            e.printStackTrace();
        }
    }
}
